<?php

/**
 * Created by bob.
 * User: bob
 * Date: 2016-5-4
 */
class OrderPush
{
    protected $appid;
    protected $secrect;
    protected $accessToken;
 
    function  __construct($appid, $secrect)
    {
        $this->appid = $appid;
        $this->secrect = $secrect;
        $this->accessToken = $this->getToken($appid, $secrect);
    }
 
 
    /**
     * 发送请求
     * @param string $url
     * @return bool|mixed
     */
	 protected function http_request($url,$data=null){
		 $curl=curl_init();
		 curl_setopt($curl,CURLOPT_URL,$url);
         curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,false);
         curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,false);
		 if(!empty($data)){
			 curl_setopt($curl,CURLOPT_POST,1);
			 curl_setopt($curl,CURLOPT_POSTFIELDS,$data);
		 }
		 curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
		 $output=curl_exec($curl);
		 curl_close($curl);
		 return $output;
	 }

    /**
     * @param $appid
     * @param $appsecret
     * @return mixed
     * 获取token
     */
    public function getToken($appid, $appsecret)
    {
       
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $appsecret;
        $token = $this->http_request($url);
        $token = json_decode(stripslashes($token));
        $arr = json_decode(json_encode($token), true);
        $access_token = $arr['access_token'];
        return $access_token;
    }
 
 
    /**
     * 发送自定义的模板消息
     * @param $touser
     * @param $template_id
     * @param $url
     * @param $data
     * @param string $topcolor
     * @return bool
     */
    public function doSend($touser, $template_id, $url, $data, $topcolor = '#7B68EE')
    {
        $template = array(
            'touser' => $touser,
            'template_id' => $template_id,
            'url' => $url,
            'topcolor' => $topcolor,
            'data' => $data
        );
        $json_template = json_encode($template);
        $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $this->accessToken;
        $dataRes = $this->http_request($url, urldecode($json_template));
        if ($dataRes['errcode'] == 0) {
            return true;
        } else {
            return false;
        }
    }
}
?>